<!--
 * @Author: zhang00001 774004514@qq.com
 * @Date: 2024-06-17 10:18:04
 * @LastEditors: yansheng 610363806@qq.com
 * @LastEditTime: 2024-07-28 00:22:02
 * @FilePath: \vue-admin\src\pages\active\ActivityForm.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <div>
    <a-drawer
      :title="formData.goods_id ? '编辑' : '新增'"
      placement="right"
      :maskClosable="false"
      :keyboard="false"
      width="800"
      @close="showAddDialog = false"
      v-model:open="showAddDialog"
    >
      <a-form
        ref="formRef"
        :rules="rules"
        :model="formData"
        label-position="top"
        :label-col="{ span: 4 }"
        :wrapper-col="{ span: 20 }"
      >
        <a-form-item
          label="商品名称"
          required
          name="goods_name"
        >
          <a-input v-model:value="formData.goods_name"></a-input>
        </a-form-item>
        <a-form-item
          label="商品图片"
          required
          name="goods_img"
        >
          <ImageUpload
            ref="uploadRef"
            :limit="5"
            :fileSize="1"
            v-model:modelValue="formData.goods_img"
          ></ImageUpload>
        </a-form-item>
        <a-form-item
          label="库存"
          required
          name="goods_stock"
        >
          <a-input-number
            id="inputNumber"
            v-model:value="formData.goods_stock"
            :min="1"
            :max="1000000"
          />
        </a-form-item>
        <a-form-item
          label="价格"
          required
          name="price"
        >
          <a-input-number
            id="inputNumber"
            v-model:value="formData.price"
            :min="1"
            :max="10000000"
          />
        </a-form-item>
        <a-form-item
          label="排序"
          required
          name="sort"
        >
          <a-input-number
            v-model:value="formData.sort"
            :min="1"
            :max="10000000"
          />
        </a-form-item>
        <a-form-item
          label="是否上架"
          name="is_on"
        >
          <a-switch
            v-model:checked="formData.is_on"
            checked-children="上架"
            un-checked-children="下架"
          />
        </a-form-item>

        <a-form-item
          label="介绍"
          required
          name="goods_details"
        >
          <Editor
            v-model:modelValue="formData.goods_details"
            :min-height="192"
          />
        </a-form-item>
        <a-form-item :wrapper-col="{ span: 14, offset: 4 }">
          <a-button @click="handleCancel">取消</a-button>
          <a-button
            style="margin-left: 20px"
            @click="previewEditDialog"
          >
            预览介绍
          </a-button>

          <a-button
            style="margin-left: 20px"
            type="primary"
            @click="handleSubmit"
          >
            确认
          </a-button>
        </a-form-item>
      </a-form>
      <previewEditor ref="previewEditorEle"></previewEditor>
    </a-drawer>
  </div>
</template>

<script setup>
  import { message } from 'ant-design-vue'
  import { extractImageUrls, deleteMultiples } from '@/utils/power.js'
  import { goodsAdd, goodsUpdate, adminDelTag } from '@/api/index.js'
  import { ref, defineEmits, defineExpose, defineProps, toRefs, nextTick } from 'vue'
  import previewEditor from '@/components/previewEditor.vue'
  import Collect from 'collect.js'
  const emits = defineEmits(['reload', 'close'])
  const props = defineProps({
    // showAddDialog: {
    //   type: Boolean,
    //   default: false
    // }
  })
  const previewEditorEle = ref(null)
  const previewEditDialog = () => {
    previewEditorEle.value.init(formData.value.goods_details)
  }
  const loading = ref(false)
  const formRef = ref()
  const rules = {
    goods_name: [
      {
        required: true,
        message: '请输入商品名称',
        trigger: 'change'
      },
      {
        min: 2,
        max: 50,
        message: '长度2-50字',
        trigger: 'blur'
      }
    ],
    goods_img: [
      {
        required: true,
        message: '请上传商品图片',
        trigger: 'change'
      }
    ],
    goods_stock: [
      {
        required: true,
        message: '请输入库存',
        trigger: 'blur'
      }
    ],
    price: [
      {
        required: true,
        message: '请输入价格',
        trigger: 'blur'
      }
    ],
    sort: [
      {
        required: true,
        message: '请输入排序',
        trigger: 'blur'
      }
    ],
    goods_details: [
      {
        required: true,
        message: '请输入介绍',
        trigger: 'blur'
      }
    ]
  }
  const showAddDialog = ref(false)
  const formData = ref({
    goods_name: '',
    goods_img: '',
    goods_stock: '',
    price: '',
    goods_details: '',
    sort: 99,
    is_on: false
  })
  const uploadVisible = ref(false)
  const handleSubmit = () => {
    formRef.value.validate().then(() => {
      loading.value = true
      let http = formData.value.goods_id ? goodsUpdate : goodsAdd
      let params
      if (formData.value.goods_id) {
        const collection = Collect(formData.value)

        const diff = collection.diffAssoc(dateRow.value)
        if (diff.items.goods_details) {
          const imageUrls = extractImageUrls(diff.items.goods_details)

          const delArrImages = Collect(richImage.value).diff(imageUrls).all()
          // 新增的图
          const newArrImages = Collect(imageUrls).diff(richImage.value).all()
          if (newArrImages.length > 0) {
            adminDelTag({ img: newArrImages })
          }

          if (delArrImages && delArrImages.length > 0) {
            deleteMultiples(delArrImages)
          }
        }
        params = {
          goods_id: formData.value.goods_id,
          ...diff.all()
        }
        if (Object.values(params).length == 1) {
        message.error('暂未修改')
        return
      }
      } else {
        params = formData.value
        const imageUrls = extractImageUrls(formData.value.goods_details)
        if(imageUrls.length > 0){
        adminDelTag({ img: imageUrls })
      }
      }
    
      http(params)
        .then((res) => {
          if (res.errorCode) {
            message.error(res.msg || '操作失败')
            return
          }
          if (res.code == 200) {
            emits('success')
            formData.value = {
              goods_name: '',
              goods_img: '',
              goods_stock: '',
              price: '',
              goods_details: '',
              sort: 99,
              is_on: false
            }
          }
          showAddDialog.value = false
          emits('reload')
        })
        .catch((err) => {
          message.error(err.msg)
        })
        .finally(() => {
          showAddDialog.value = false
          loading.value = false
        })
    })
  }

  const handleCancel = () => {
    showAddDialog.value = false
    emits('close') // Close the dialog
  }
  const dateRow = ref()
  const richImage = ref(null)
  const init = (row) => {
    showAddDialog.value = true
    nextTick(() => {
      formRef.value.resetFields()

      if (row) {
        let data = JSON.parse(JSON.stringify(row))
        dateRow.value = JSON.parse(JSON.stringify(row))
        formData.value = {
          goods_id: data.goods_id,
          goods_name: data.goods_name,
          goods_img: data.goods_img,
          goods_stock: data.goods_stock,
          price: data.price,
          goods_details: data.goods_details,
          sort: data.sort,
          is_on: data.is_on
        }
        richImage.value = extractImageUrls(data.goods_details)
      }
    })
    //
  }
  defineExpose({
    init
  })
</script>

<style scoped></style>
